package splitframe.farm.computefarm;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import net.jini.core.discovery.LookupLocator;

import org.tiling.computefarm.impl.javaspaces.util.ClassServer;
import org.tiling.computefarm.impl.javaspaces.worker.MulticastWorker;

import splitframe.farm.serviceutil.MulticastServiceUtil;

public class WorkerRunner extends MulticastWorker {

	private static final long serialVersionUID = 130587923673139395L;
	private static ClassServer classServer;
	private static Logger log = Logger.getLogger(WorkerRunner.class.toString());
	
	public WorkerRunner(LookupLocator[] lookupLocators) {
		super(lookupLocators);
	}
	
    public static void main(String[] args) throws Throwable {
    	turnOffUrlConnectionCaching();
		startClassServer();
		setCodebase();
		LookupLocator[] lookupLocators = new LookupLocator[args.length];
		
		for (int i = 0; i < args.length; i++) {
			lookupLocators[i] = new LookupLocator(args[i]);
		}
		WorkerRunner worker = new WorkerRunner(lookupLocators);
		worker.run();
    }

    /**
     * method copied from MulticastWorker
     * @see org.tiling.computefarm.impl.javaspaces.worker.MulticastWorker
     * @throws IOException
     * @throws MalformedURLException
     */
	private static void turnOffUrlConnectionCaching() throws IOException, MalformedURLException {
	    if (Boolean.getBoolean("org.tiling.computefarm.impl.javaspaces.DontReloadClasses")) {
	    	return;
		}		
		new URL("http://localhost/").openConnection().setDefaultUseCaches(false);
	}

	/**
     * method copied from MulticastWorker
     * @see org.tiling.computefarm.impl.javaspaces.worker.MulticastWorker
	 * @throws IOException
	 */
	private static void startClassServer() throws IOException {
		classServer = new ClassServer(ClassServer.DEFAULT_ROOT, ClassServer.DEFAULT_START_PORT_NUMBER, false);
	    classServer.start();
	}
	
	private static void setCodebase()
	{
		String codebase = "";
		try {
			MulticastServiceUtil multicastServiceUtil = new MulticastServiceUtil(false);
			codebase = multicastServiceUtil.getCodebaseUrl();
			
			System.setProperty("java.rmi.server.codebase",codebase);
			System.setProperty("org.tiling.computefarm.rmi.server.codebase.template",codebase);
			log.info("codebase url: " + codebase);
			
			multicastServiceUtil = null;
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}
